package com.zjzywl.smoke.authenticate;

import com.zjzywl.smoke.repository.AuthorityRepository;
import com.zjzywl.smoke.repository.RoleRepository;
import com.zjzywl.smoke.repository.SysUserRepository;
import com.zjzywl.smoke.entity.Authority;
import com.zjzywl.smoke.entity.Role;
import com.zjzywl.smoke.entity.SysUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements UserDetailsService {
	@Autowired
	private SysUserRepository userRepository;
	@Autowired
	private RoleRepository roleRepository;	
	@Autowired 
	private AuthorityRepository authorityRepository;	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		List<SimpleGrantedAuthority> roles = new ArrayList<SimpleGrantedAuthority>();
		SysUser people = userRepository.findByLoginName(username);
	if (people != null) {
			Role role = people.getRole();
			Authority authority=authorityRepository.findRoleById(role.getRoleId());
			if(authority.getManage().equals("1")) {
				roles.add(new SimpleGrantedAuthority("manage"));
			}
			if(authority.getFront().equals("1")) {
				roles.add(new SimpleGrantedAuthority("front"));
			}
			if(authority.getFireAlarm().equals("1")) {
				roles.add(new SimpleGrantedAuthority("fireAlarm"));
			}
			if(authority.getBigData().equals("1")) {
				roles.add(new SimpleGrantedAuthority("bigData"));
			}
			if(authority.getSmallData().equals("1")) {
				roles.add(new SimpleGrantedAuthority("smallData"));
			}
//			if (role.equals("0") || role.equals("2")) {
//				roles.add(new SimpleGrantedAuthority("admin"));
//			}
//			if (role.equals("1") || role.equals("2")) {
//				roles.add(new SimpleGrantedAuthority("viewer"));
//			}
			return new AuthUser(people, roles);
		}
	return null;
	}
}
